use crate::G_DLL_HANDLE;
use encoding_rs::GBK;
use std::ffi::{CString, OsStr};
use std::os::windows::ffi::OsStrExt;
use std::sync::atomic::Ordering;
use winapi::shared::minwindef::HMODULE;
use winapi::um::libloaderapi::GetModuleFileNameW;
use winapi::um::sysinfoapi::GetSystemDirectoryW;

/// 辅助函数：将UTF-8字符串转换为GBK编码的CString
pub fn utf8_to_gbk(text: &str) -> CString {
    let (gbk_data, _, _) = GBK.encode(text);
    CString::new(gbk_data.to_vec()).unwrap()
}

// 辅助函数：将字符串转换为宽字符串（UTF-16）
pub fn to_widestring(s: &str) -> Vec<u16> {
    OsStr::new(s)
        .encode_wide()
        .chain(std::iter::once(0))
        .collect()
}

// 辅助函数：获取System32目录路径
pub fn get_system32_directory() -> Option<String> {
    let mut buffer = vec![0u16; 260]; // MAX_PATH = 260
    let len = unsafe { GetSystemDirectoryW(buffer.as_mut_ptr(), buffer.len() as u32) };

    if len == 0 {
        return None;
    }

    // 截断到实际长度
    buffer.truncate(len as usize);

    String::from_utf16(&buffer).ok()
}

/// 获取当前DLL的路径
pub fn get_current_dll_path() -> Option<Vec<u16>> {
    let mut buffer = vec![0u16; 260];

    // 使用保存的 DLL 句柄
    let h_module = G_DLL_HANDLE.load(Ordering::SeqCst) as HMODULE;

    let len = unsafe { GetModuleFileNameW(h_module, buffer.as_mut_ptr(), buffer.len() as u32) };

    if len == 0 {
        return None;
    }

    buffer.truncate(len as usize);

    // 用于调试 - 显示获取到的路径
    if let Ok(path) = String::from_utf16(&buffer) {
        // 如果你有消息框函数的话
        // show_messagebox("获取dll路径", &path, MB_ICONINFORMATION);
        println!("DLL Path: {}", path);
    }

    Some(buffer)
}
